﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml;

using Enyim.Caching.Configuration;
using System.IO;

namespace AFT.Parking.Foundation.Caching
{
    /// <summary>
    /// Memcached 配置文件
    /// </summary>
    public static class MemcachedConfig
    {
        public static IMemcachedClientConfiguration config 
        {
            get 
            { 
                var c = new MemcachedClientConfiguration();
                LoadConfig();

                // 设置 Server
                if (serverList != null && serverList.Count > 0)
                {
                    // ip必须类似为“192.168.1.1：1000”的IP + Port形式
                    foreach (var s in serverList)
                    {
                        c.AddServer(s);
                    }
                }

                // 设置 Socket Pool
                c.SocketPool.ConnectionTimeout = conTime;
                c.SocketPool.DeadTimeout = deadTime;
                c.SocketPool.MaxPoolSize = maxPoolSize;
                c.SocketPool.MinPoolSize = minPoolSize;
                c.SocketPool.QueueTimeout = queueTime;
                return c;
            }
        }

        private static XmlDocument xmlDocument;
        private static List<string> serverList = new List<string>();
        private static int maxPoolSize = 100;
        private static int minPoolSize = 10;
        private static TimeSpan conTime;
        private static TimeSpan deadTime;
        private static TimeSpan queueTime;

        private static void LoadConfig()
        {
            if (xmlDocument == null)
            {
                FileInfo fileInfo = new FileInfo(string.Format("{0}Memcached.config", AppDomain.CurrentDomain.BaseDirectory));
                //判断配置文件是否存在
                if (fileInfo.Exists)
                {
                    try
                    {
                        //将配置文件Load进XmlDocument，以便进行相关操作
                        FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
                        XmlReader xmlReader = XmlReader.Create(fileStream);
                        xmlDocument = new XmlDocument();
                        xmlDocument.Load(xmlReader);

                        //服务端节点列表
                        XmlNode xmlNode = xmlDocument.SelectSingleNode("/memcached/servers");
                        if (xmlNode.ChildNodes != null && xmlNode.ChildNodes.Count > 0)
                        {
                            foreach (XmlNode n in xmlNode.ChildNodes)
                            {
                                serverList.Add(n.Attributes["address"].Value + ":" + n.Attributes["port"].Value);
                            }
                        }
                        else
                        {
                            throw new Exception("必须配置至少一个服务端节点！");
                        }

                        if (!int.TryParse(xmlDocument.SelectSingleNode("/memcached/socketPool/minPoolSize").InnerText, out minPoolSize))
                        {
                            throw new Exception("minPoolSize必须为int类型！");
                        }
                        if (!int.TryParse(xmlDocument.SelectSingleNode("/memcached/socketPool/maxPoolSize").InnerText, out maxPoolSize))
                        {
                            throw new Exception("maxPoolSize必须为int类型！");
                        }
                        if (!TimeSpan.TryParse(xmlDocument.SelectSingleNode("/memcached/socketPool/connectionTimeout").InnerText, out conTime))
                        {
                            throw new Exception("connectionTimeout必须为Timespan类型！");
                        }
                        if (!TimeSpan.TryParse(xmlDocument.SelectSingleNode("/memcached/socketPool/deadTimeout").InnerText, out deadTime))
                        {
                            throw new Exception("deadTimeout必须为Timespan类型！");
                        }
                        if (!TimeSpan.TryParse(xmlDocument.SelectSingleNode("/memcached/socketPool/queueTimeout").InnerText, out queueTime))
                        {
                            throw new Exception("queueTimeout必须为Timespan类型！");
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
                else
                {
                    throw new Exception("Memcached.config配置文件不存在");
                }
            }
        }
    }
}
